package gcb.metalsys.controller.cop;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import gcb.metalsys.entity.cop.CopDepartment;
import gcb.metalsys.dto.cop.WarehouseDTO;
import gcb.metalsys.entity.auth.AuthUser;
import gcb.metalsys.entity.cop.*;
import gcb.metalsys.enums.ProductEnum;
import gcb.metalsys.service.auth.AuthUserService;
import gcb.metalsys.service.cop.CopCompanyService;
import gcb.metalsys.service.cop.CopDepartmentService;
import gcb.metalsys.service.cop.CopProductService;
import org.apache.catalina.WebResource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import gcb.metalsys.base.ResultUtil;
import gcb.metalsys.base.dto.ResultDTO;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import gcb.metalsys.service.cop.CopWarehouseService;

/**
 * @since 2020-07-15
 */
@RestController
@RequestMapping("/copWarehouse")
public class CopWarehouseController {

    private final CopWarehouseService copWarehouseService;
    private final AuthUserService authUserService;
    private final CopProductService copProductService;
    private final CopCompanyService copCompanyService;
    private final CopDepartmentService copDepartmentService;

    @Autowired
    public CopWarehouseController(CopWarehouseService copWarehouseService, AuthUserService authUserService, CopProductService copProductService, CopCompanyService copCompanyService, CopDepartmentService copDepartmentService) {
        this.copWarehouseService = copWarehouseService;
        this.authUserService = authUserService;
        this.copProductService = copProductService;
        this.copCompanyService = copCompanyService;
        this.copDepartmentService = copDepartmentService;
    }

    @PostMapping
    @ApiOperation(value = "插入")
    public ResultDTO insertOne(@RequestBody CopWarehouse copWarehouse) throws Exception {
        copWarehouseService.save(copWarehouse);
        return ResultUtil.Success(copWarehouse);
    }

    @DeleteMapping("/{id:\\d+}")
    @ApiOperation("按ID删除")
    public ResultDTO deleteById(@PathVariable Long id) throws Exception {
        copWarehouseService.removeById((long) id);
        return ResultUtil.Success();
    }

    @GetMapping("/user")
    public ResultDTO selectEntityPage(Authentication authentication,
                                      @RequestParam(value = "page", defaultValue = "0") int pageNum,
                                      @RequestParam(value = "limit", defaultValue = "8") int pageSize)throws Exception{
        AuthUser userDetails = authUserService.getUserDetails(authentication);

        QueryWrapper<CopWarehouse> copWarehouseQueryWrapper = new QueryWrapper<>();
        copWarehouseQueryWrapper.eq("user_id",userDetails.getUserId());
        IPage<CopWarehouse> page = copWarehouseService.page(new Page<CopWarehouse>(pageNum, pageSize), copWarehouseQueryWrapper);
        List<CopWarehouse> copWarehouses = page.getRecords();
        int count = (int) page.getTotal();

        List<WarehouseDTO> result = Converter(copWarehouses);
        return ResultUtil.Success(result,count);
    }

    @GetMapping("/department")
    public ResultDTO selectDepartmentWarehouse(Authentication authentication,
                                      @RequestParam(value = "page", defaultValue = "0") int pageNum,
                                      @RequestParam(value = "limit", defaultValue = "8") int pageSize)throws Exception{
        List<CopDepartment> departments = copDepartmentService.getMyselfAndChildId(authentication);
        List<Long> departmentId = departments.stream().map(CopDepartment::getDepartmentId).collect(Collectors.toList());
        QueryWrapper<CopWarehouse> copWarehouseQueryWrapper = new QueryWrapper<>();
        copWarehouseQueryWrapper.in("department_id",departmentId);
        IPage<CopWarehouse> page = copWarehouseService.page(new Page<CopWarehouse>(pageNum, pageSize), copWarehouseQueryWrapper);
        List<CopWarehouse> copWarehouses = page.getRecords();
        int count = (int) page.getTotal();
        List<WarehouseDTO> result = Converter(copWarehouses);
        return ResultUtil.Success(result,count);
    }

    @GetMapping("/myself")
    public ResultDTO selectMyWarehouse(Authentication authentication)throws Exception{
        AuthUser userDetails = authUserService.getUserDetails(authentication);

        QueryWrapper<CopWarehouse> copWarehouseQueryWrapper = new QueryWrapper<>();
        copWarehouseQueryWrapper.eq("user_id",userDetails.getUserId());
        List<CopWarehouse> copWarehouses = copWarehouseService.list(copWarehouseQueryWrapper);

        List<WarehouseDTO> result = Converter(copWarehouses);
        return ResultUtil.Success(result,copWarehouses.size());
    }


    private List<WarehouseDTO> Converter(List<CopWarehouse> copWarehouses){
        //获取产品列表
        Set<Long> productId = copWarehouses.stream().map(CopWarehouse::getProductId).collect(Collectors.toSet());
        QueryWrapper<CopProduct> copProductQueryWrapper = new QueryWrapper<>();
        copProductQueryWrapper.in("product_id", productId);
        List<CopProduct> productList = copProductService.list(copProductQueryWrapper);

        //获取公司列表
        Set<String> companyNumber = productList.stream().map(CopProduct::getCompanyNumber).collect(Collectors.toSet());
        QueryWrapper<CopCompany> copCompanyQueryWrapper = new QueryWrapper<>();
        copCompanyQueryWrapper.in("company_number", companyNumber);
        List<CopCompany> companyList = copCompanyService.list(copCompanyQueryWrapper);

        //获取部门列表
        Set<Long> departmentId = copWarehouses.stream().map(CopWarehouse::getDepartmentId).collect(Collectors.toSet());
        QueryWrapper<CopDepartment> copDepartmentQueryWrapper = new QueryWrapper<>();
        copDepartmentQueryWrapper.in("department_id", departmentId);
        List<CopDepartment> departmentList = copDepartmentService.list(copDepartmentQueryWrapper);
        //获取人员列表
        Set<Long> userId = copWarehouses.stream().map(CopWarehouse::getUserId).collect(Collectors.toSet());
        QueryWrapper<AuthUser> authUserQueryWrapper = new QueryWrapper<>();
        copDepartmentQueryWrapper.in("user_id", userId);
        List<AuthUser> userList = authUserService.list(authUserQueryWrapper);

        //转换成DTO
        List<WarehouseDTO> result = new ArrayList<>();
        for (CopWarehouse copWarehouse : copWarehouses) {
            WarehouseDTO warehouseDTO = new WarehouseDTO();
            BeanUtils.copyProperties(copWarehouse,warehouseDTO);
            for (CopProduct product : productList) {
                if (product.getProductId().equals(copWarehouse.getProductId())) {
                    warehouseDTO.setProductName(product.getProductName());
                    warehouseDTO.setProductNumber(product.getProductNumber());
                    warehouseDTO.setProductId(product.getProductId());
                    warehouseDTO.setCompanyNumber(product.getCompanyNumber());
                    break;
                }
            }
            for (CopCompany copCompany : companyList) {
                if (copCompany.getCompanyNumber().equals(warehouseDTO.getCompanyNumber())) {
                    warehouseDTO.setCompanyName(copCompany.getCompanyName());
                    break;
                }
            }
            for (CopDepartment department : departmentList) {
                if (department.getDepartmentId().equals(copWarehouse.getDepartmentId())) {
                    warehouseDTO.setDepartmentName(department.getDepartmentName());
                    break;
                }
            }
            for (AuthUser authUser : userList) {
                if (authUser.getUserId().equals(copWarehouse.getUserId())) {
                    warehouseDTO.setUserName(authUser.getUserTrueName());
                    break;
                }
            }
            result.add(warehouseDTO);
        }
        return result;
    }

    @GetMapping("/pieList/{id}")
    @ApiOperation("查询库存饼图统计，返回")
//    public ResultDTO selectPieList(@PathVariable CopDepartment copDepartment)throws Exception{
    public ResultDTO selectPieList(@PathVariable Long id)throws Exception{
        List<CopWarehouse> list = copWarehouseService.getPieListById(id);
        for (CopWarehouse c:list){
            System.out.println(c);
        }
//        return ResultUtil.Success(copWarehouseService.getPieListById(copDepartment.getDepartmentId()));
        return ResultUtil.Success(list);
    }

    @GetMapping("/tableList/{id}")
    @ApiOperation("查询表格本月出库数统计")
    public ResultDTO countTableMonthOutList(@PathVariable Long id)throws Exception{
        List<CopWarehouse> list = copWarehouseService.countTableListMonthOutById(id);
        for (CopWarehouse c:list){
            System.out.println(c);
        }
//        return ResultUtil.Success(copWarehouseService.getPieListById(copDepartment.getDepartmentId()));
        return ResultUtil.Success(list);
    }

}
